package com.example.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.edu.entity.Subject;
import com.example.edu.entity.excel.SubjectData;
import com.example.edu.service.SubjectService;

public class EasyExcelSubjectListener extends AnalysisEventListener<SubjectData>{
	
	SubjectService subjectService;

	public EasyExcelSubjectListener() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public EasyExcelSubjectListener(SubjectService subjectService) {
		super();
		// TODO Auto-generated constructor stub
		this.subjectService = subjectService;
	}

	@Override
	public void invoke(SubjectData data, AnalysisContext context) {
		// TODO Auto-generated method stub
		Subject existOneSubjects = existOneSubject(data.getOneSubjectName(), subjectService);
		
		if(existOneSubjects==null) {
			
			String oneSubjectName = data.getOneSubjectName();
			Subject subject = new Subject();
			subject.setParentId("0");
			subject.setTitle(oneSubjectName);
			
			subjectService.save(subject);
		};
		
		
		
		if(existTwoSubject(data.getTwoSubjectName(), existOneSubject(data.getOneSubjectName(), subjectService).getId(),subjectService)==null) {
			
			Subject subject = new Subject();
			subject.setParentId(existOneSubject(data.getOneSubjectName(), subjectService).getId());
			subject.setTitle(data.getTwoSubjectName());
			
			subjectService.save(subject);
		};
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		// TODO Auto-generated method stub
		
	}
	
	public Subject existOneSubject(String name,SubjectService subjectService) {
		
		QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("title", name);
		queryWrapper.eq("parent_id", "0");
		return subjectService.getOne(queryWrapper);
	}
	
	public Subject existTwoSubject(String name,String pid,SubjectService subjectService) {
		
		QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("title", name);
		queryWrapper.eq("parent_id", pid);
		return subjectService.getOne(queryWrapper);	
	}

}
